package com.drought.rained.ui.activity;

import android.annotation.SuppressLint;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.drought.rained.BuildConfig;
import com.drought.rained.R;
import com.drought.rained.LJApplication;
import com.drought.rained.adapter.FragmentAdapterLJ;
import com.drought.rained.base.BaseTitleActivity;
import com.drought.rained.business.RouterMapLJ;
import com.drought.rained.cache.AcacheLJ;
import com.drought.rained.cache.AcacheKeysLJ;
import com.drought.rained.cache.UserInfoLJ;
import com.drought.rained.permission.IPermissonLJ;
import com.drought.rained.permission.PermissionLJ;
import com.drought.rained.rxbus.EventMsgLJ;
import com.drought.rained.rxbus.EventsLJ;
import com.drought.rained.rxbus.RxBusLJ;
import com.drought.rained.ui.fragment.LoanFragmentLJ;
import com.drought.rained.ui.fragment.MineFragmentLJ;
import com.drought.rained.utils.ToastUtilsLJ;
import com.drought.rained.view.GrantPermissionDialogLJ;
import com.drought.rained.view.MyViewPagerLJ;
import com.drought.rained.view.UpdateVersionDialogLJ;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

@Route(name = "首页", path = RouterMapLJ.MAIN_ACTIVITY_PAGE)
public class MainActivityLJ extends BaseTitleActivity implements IPermissonLJ {

    @BindView(R.id.view_pager)
    MyViewPagerLJ viewPager;
    @BindView(R.id.tab_loan)
    TextView tabLoan;
    @BindView(R.id.tab_mine)
    TextView tabMine;

    private FragmentAdapterLJ fragmentAdapter;
    private GrantPermissionDialogLJ grantPermissionDialog;
    private UpdateVersionDialogLJ updateVersionDialog;
    private PermissionLJ permission;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        viewPager.setAdapter(getFragmentAdapter());
        viewPager.setOffscreenPageLimit(2);
        viewPager.setCurrentItem(0);
        tabLoan.setSelected(true);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onUIReady() {
        RxBusLJ.getInstance().toObservable().map(new Function<Object, EventMsgLJ>() {
            @Override
            public EventMsgLJ apply(Object o) throws Exception {
                return (EventMsgLJ) o;
            }
        }).subscribe(new Consumer<EventMsgLJ>() {
            @Override
            public void accept(EventMsgLJ eventMsg) throws Exception {
                if (EventsLJ.LOGOUT.equals(eventMsg.getMsg())) {
                    viewPager.setCurrentItem(0);
                    tabLoan.setSelected(true);
                    tabMine.setSelected(false);
                }
            }
        });
        // 检查权限
        checkAppPermission();
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_main_lj;
    }

    private FragmentAdapterLJ getFragmentAdapter() {
        if (fragmentAdapter == null) {
            List<Fragment> fragmentList = new ArrayList<>();
            LoanFragmentLJ loanFragment = new LoanFragmentLJ();
            MineFragmentLJ mineFragment = new MineFragmentLJ();
            fragmentList.add(loanFragment);
            fragmentList.add(mineFragment);
            fragmentAdapter = new FragmentAdapterLJ(getSupportFragmentManager(), fragmentList);
        }
        return fragmentAdapter;
    }

    @OnClick({R.id.tab_loan, R.id.tab_mine})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tab_loan:
                tabLoan.setSelected(true);
                tabMine.setSelected(false);
                viewPager.setCurrentItem(0);
                break;
            case R.id.tab_mine:
                if (UserInfoLJ.isLogin()) {
                    tabLoan.setSelected(false);
                    tabMine.setSelected(true);
                    viewPager.setCurrentItem(1);
                } else {
                    ARouter.getInstance().build(RouterMapLJ.FACEBOOKLOGIN).navigation();
                    ToastUtilsLJ.showShort(this, R.string.login_not_login);
                }
                break;
        }
    }

    private void checkAppPermission() {
        permission = new PermissionLJ(this, this);
        String cache = AcacheLJ.get(LJApplication.getContext()).getAsString(AcacheKeysLJ.GRANT);
        int grant = Integer.valueOf(TextUtils.isEmpty(cache) ? "0" : cache);
        if (grant != BuildConfig.grant) {
            grantPermissionDialog = new GrantPermissionDialogLJ(MainActivityLJ.this);
            grantPermissionDialog.show();
            grantPermissionDialog.setOnClickListener(new GrantPermissionDialogLJ.GrantPermissionDialogCallBack() {
                @Override
                public void onConfirm() {
                    permission.requestAll();
                }

                @Override
                public void onCancel() {
                    grantPermissionDialog.hide();
                    finish();
                }
            });
        }
    }

    @Override
    public void onSuccess(int result) {
        AcacheLJ.get(LJApplication.getContext()).put(AcacheKeysLJ.GRANT, String.valueOf(BuildConfig.grant));
        grantPermissionDialog.hide();
    }
}